package cn.itsource.xhy.user.service.impl;

import cn.itsource.xhy.basic.service.impl.BaseServiceImpl;
import cn.itsource.xhy.user.contants.UserContants;
import cn.itsource.xhy.user.contants.WxInfoContants;
import cn.itsource.xhy.user.controller.WxUserContorller;
import cn.itsource.xhy.user.domain.LoginInfo;
import cn.itsource.xhy.user.domain.User;
import cn.itsource.xhy.user.domain.WxUser;
import cn.itsource.xhy.user.mapper.LoginInfoMapper;
import cn.itsource.xhy.user.mapper.UserMapper;
import cn.itsource.xhy.user.mapper.WxUserMapper;
import cn.itsource.xhy.user.service.IWxUserService;
import cn.itsource.xhy.utils.AjaxResult;
import cn.itsource.xhy.utils.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class WxUserServiceImpl extends BaseServiceImpl<WxUser> implements IWxUserService {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Override
    public AjaxResult login(Map<String, String> map) {
        // 获取code
        String code = map.get("code");
        String url = WxInfoContants.GET_ACCESSTOKEN
                .replace("APPID",WxInfoContants.APPID)
                .replace("SECRET",WxInfoContants.SECRET)
                .replace("CODE",code);
        // 获取openId，access——token
        String WxData = HttpUtil.sendGet(url);
        System.out.println(WxData);
        // 工具类解析json
        JSONObject object = JSON.parseObject(WxData);
        String openid = object.getString("openid");
        String access_token = object.getString("access_token");
        // 判断是否是第一次使用微信
        WxUser wxUser = wxUserMapper.findByOpendId(openid);
        // 都不为null 是老用户则免密登录
        if (wxUser != null && wxUser.getUser() != null){
            // 用微信中的user对象拿到id去查询
            LoginInfo loginInfo = loginInfoMapper.findByUid(wxUser.getUser().getId());
            return noPwd(loginInfo);
        } else { // 新用户跳转到绑定页面

            return new AjaxResult("/bindwechart.html?openid="+openid+"&access_token="+access_token);
        }
    }

    // 绑定
    @Override
    public AjaxResult bind(Map<String, String> map) {
        String phone = map.get("phone");
        String Wxcode = map.get("code");
        String openId = map.get("openId");
        String access_token = map.get("access_token");
        // 判断验证是否正确
        String codeInRedis = (String)redisTemplate.opsForValue().get(UserContants.BIND_CODE+":"+phone);
        // 分割拿到验证码
        String code = codeInRedis.split(":")[0];
        // 判断与发送的是否一直
        if (!code.equals(Wxcode)){
            throw new RuntimeException("验证码有误，请重新输入");
        }
        // 判断输入的手机号是否已经存在
        User user = userMapper.findByPhone(phone);
        LoginInfo loginInfo = null;
        if (user == null){
            // 没注册过，新生成
            user = new User();
            user.setPhone(phone);
            user.setState(1);
            user.setUsername("p_"+phone);
            // 保存user
            userMapper.save(user);
            // 将user对象转换成loginInfo
            loginInfo = userToLoginInfo(user);
            loginInfoMapper.save(loginInfo);
        }
        // 获取微信信息，保存到数据库
        String url = WxInfoContants.GET_USERINFO
                .replace("ACCESS_TOKEN",access_token)
                .replace("OPENID",openId);
        String WxData = HttpUtil.sendGet(url);
        System.out.println(WxData);
        //工具类转换
        JSONObject parseObject = JSON.parseObject(WxData);
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(parseObject.getString("openid"));
        wxUser.setNickname(parseObject.getString("setNickname"));
        wxUser.setSex(parseObject.getInteger("sex"));
        wxUser.setAddress(parseObject.getString("country")
                +parseObject.getString("province")
                +parseObject.getString("city"));
        wxUser.setUnionid(parseObject.getString("unionid"));
        wxUser.setUser(user);
        // 保存
        wxUserMapper.save(wxUser);
        if (loginInfo == null){
            // 如果是老用户则找到对象的loginInfo
            loginInfo = loginInfoMapper.findByUid(user.getId());
        }
        // 绵密登录
        return noPwd(loginInfo);
    }

    // 将user对象转换为LonginInfo对象
    private LoginInfo userToLoginInfo(User user){
        LoginInfo loginInfo = new LoginInfo();
        // gjl复制数据
        BeanUtils.copyProperties(user,loginInfo);
        // 其他数据赋值
        loginInfo.setDisable(1);
        loginInfo.setType(1);
        loginInfo.setUId(user.getId());
        return loginInfo;
    }


    private AjaxResult noPwd(LoginInfo loginInfo){
        // UUID拿到token
        String token = UUID.randomUUID().toString();
        // 将当前用户放在session中
        redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
        HashMap<String, Object> map = new HashMap<>();
        // 将数据装在map
        map.put("token",token);
        // 将敏感数据清空
        loginInfo.setPassword("");
        loginInfo.setSalt("");
        map.put("loginInfo",loginInfo);
        return AjaxResult.me().setResultObj(map);
    }
}
